<script setup lang="tsx">
import { Button, Popconfirm, Switch } from 'ant-design-vue';
import dayjs from 'dayjs';
import { ref } from 'vue';
import { useTable, useTableOperate, useTableScroll } from '@/hooks/common/table';
import { $t } from '@/locales';
import { getUserListApi, userDeleteApi, userEditApi } from '@/service/api/businessApi';
import { unitHooks } from '@/views/systemManage/unitManage/unitHooks';
import { userHooks } from '@/views/systemManage/userManage/userHooks';
import UserOperateDrawer from './modules/user-operate-drawer.vue';
import UserSearch from './modules/user-search.vue';

const { tableWrapperRef, scrollConfig } = useTableScroll();
const { getUnitList } = unitHooks();
const { getUserTypeText } = userHooks();

const unitList: any = ref([]);
(async () => {
  unitList.value = await getUnitList();
})();

const changeLocked = async (locked: any, id: any) => {
  await userEditApi({
    locked,
    id
  });
  await getData();
};

const changeReceiveAlarm = async (receiveAlarm: any, id: any) => {
  await userEditApi({
    receiveAlarm,
    id
  });
  await getData();
};

const switchChange = (checked: any, record: any, type: any) => {
  // 1 是否锁定， 2 是否接收警告
  if (type === 1) {
    record.locked = checked;
    changeLocked(checked, record.id);
  }
  if (type === 2) {
    record.receiveAlarm = checked;
    changeReceiveAlarm(checked, record.id);
  }
};

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: getUserListApi,
  apiParams: {
    pageNo: 1,
    pageSize: 10,
    locked: '',
    userType: '',
    sex: ''
  },
  columns: (): any => [
    {
      key: 'loginCode',
      dataIndex: 'loginCode',
      title: '用户账户',
      width: 180,
      fixed: 'left'
    },
    {
      key: 'userName',
      dataIndex: 'userName',
      title: '用户名称',
      width: 160
    },
    {
      title: '用户性别',
      dataIndex: 'sex',
      key: 'sex',
      width: 100
    },
    {
      title: '用户类型',
      dataIndex: 'userType',
      key: 'userType',
      width: 160,
      customRender: ({ record }: any) => {
        return getUserTypeText(record.userType);
      }
    },
    {
      title: '是否锁定',
      dataIndex: 'locked',
      key: 'locked',
      width: 160,
      customRender: ({ record }: any) => {
        return (
          <Switch
            onChange={val => switchChange(val, record, 1)}
            checked={record.locked}
            checked-children="是"
            un-checked-children="否"
          />
        );
      }
    },
    // {
    //   title: '是否接收警告',
    //   dataIndex: 'receiveAlarm',
    //   key: 'receiveAlarm',
    //   width: 160,
    //   customRender: ({ record }: any) => {
    //     return (
    //       <Switch
    //         onChange={val => switchChange(val, record, 2)}
    //         checked={record.receiveAlarm}
    //         checked-children="是"
    //         un-checked-children="否"
    //       />
    //     );
    //   }
    // },
    // {
    //   title: '是否关注公众号',
    //   dataIndex: 'subscribed',
    //   key: 'subscribed',
    //   width: 160,
    //   customRender: ({ record }: any) => {
    //     return record.subscribed ? '是' : '否';
    //   }
    // },
    {
      title: '所属单位',
      dataIndex: 'orgId',
      key: 'orgId',
      width: 160,
      ellipsis: true,
      customRender: ({ record }: any) => {
        return unitList.value.find((n: any) => n.id === record.orgId)?.name;
      }
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      key: 'gmtCreate',
      width: 160,
      customRender: ({ record }: any) => {
        return dayjs(record.gmtCreate).format('YYYY-MM-DD HH:mm:ss');
      }
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      key: 'gmtModified',
      width: 160,
      customRender: ({ record }: any) => {
        return dayjs(record.gmtModified).format('YYYY-MM-DD HH:mm:ss');
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 140,
      fixed: 'right',
      customRender: ({ record }: any) => (
        <div class="flex-center gap-8px">
          <Button type="primary" ghost size="small" onClick={() => edit(record.id)}>
            编辑
          </Button>
          <Popconfirm title="确认删除吗？" onConfirm={() => handleDelete(record.id)}>
            <Button danger size="small">
              删除
            </Button>
          </Popconfirm>
        </div>
      )
    }
  ]
});

const { drawerVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onDeleted } = useTableOperate(
  data as any,
  getData
);

async function handleDelete(id: any) {
  const res = await userDeleteApi(id);
  if (res.error === null) await onDeleted();
}

function edit(id: number) {
  handleEdit(id);
}

const authorityModalVisible = ref(false);
const authorityUserId = ref();
const openAuthorityModal = (id: any) => {
  authorityModalVisible.value = true;
  authorityUserId.value = id;
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <UserSearch v-model:model="searchParams" :unit-list="unitList" @reset="resetSearchParams" @search="getDataByPage" />
    <ACard
      :title="$t('page.manage.user.title')"
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @refresh="getData"
        />
      </template>
      <ATable
        ref="tableWrapperRef"
        :columns="columns"
        :data-source="data"
        size="small"
        :scroll="scrollConfig"
        :loading="loading"
        row-key="id"
        :pagination="mobilePagination"
        class="h-full"
        children-column-name="childDeviceInfo"
      />

      <UserOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :unit-list="unitList"
        :row-data="editingData"
        @submitted="getData"
      />

    </ACard>
  </div>
</template>

<style scoped></style>
